import 'dart:ui';

import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_book/data/model/book_chapter_model.dart';
import 'package:flutter_book/page/book/animation_util/animation/animation_page_slide.dart';
import 'package:flutter_book/page/book/controller/book_page_controller.dart';
import '../animation/animation_page_base.dart';
import '../animation/animation_page_simulation_turn.dart';
import '../data/animation_type.dart';
import '../util/touch_event.dart';
import 'dart:ui' as ui;

import 'widget_reader_painter.dart';

class ReaderPageManager {
  late BaseAnimationPage currentAnimationPage;
  GlobalKey canvasKey;
  AnimationController animationController;

  ReaderPageManager({
    required int animationType,
    required this.canvasKey,
    required this.animationController}){
    _setCurrentAnimation(animationType);
    _setAnimationController();
  }

  late TouchEvent currentTouchData;

  int currentAnimationType = 0;

  STATE? currentState;

  //设置数据源
  setBookContentController(BookPageController bookPageController) async {
    await currentAnimationPage.setBookContentController(bookPageController);
  }

  //设置点击事件
  onTapListener(Function? onTap) {
    currentAnimationPage.onTapListener(onTap);
  }

  //设置长按事件
  onLongTapListener(Function? onLongTap) {
    currentAnimationPage.onLongTapListener(onLongTap);
  }

  //设置动画
  _setCurrentAnimation(int animationType) {
    currentAnimationType = animationType;
    switch (animationType) {
      case AnimationType.TYPE_ANIMATION_SIMULATION_TURN:
        currentAnimationPage = SimulationTurnPageAnimation();
        break;
      case AnimationType.TYPE_ANIMATION_COVER_TURN:

        currentAnimationPage = SimulationTurnPageAnimation();
        // currentAnimationPage = CoverPageAnimation();
        break;
      case AnimationType.TYPE_ANIMATION_SLIDE_TURN:
        currentAnimationPage = SimulationTurnPageAnimation();
        break;
      default:
        currentAnimationPage = SimulationTurnPageAnimation();
        break;
    }
  }



  //设置手势监听的结果
  void setCurrentTouchEvent(TouchEvent event) {
    /// 如果正在执行动画，判断是否需要中止动画
    if (currentState == STATE.STATE_ANIMATING) {
      if (currentAnimationPage.isShouldAnimatingInterrupt()) {
        if (event.action == TouchEvent.ACTION_DOWN) {
          interruptCancelAnimation();
        }
      } else {
        return;
      }
    }

    /// 用户抬起手指后，是否需要执行动画
    if (event.action == TouchEvent.ACTION_UP ||
        event.action == TouchEvent.ACTION_CANCEL) {

      switch (currentAnimationType) {
        case AnimationType.TYPE_ANIMATION_SIMULATION_TURN:
        case AnimationType.TYPE_ANIMATION_COVER_TURN:
          if (currentAnimationPage.isCancelArea()!) {
            startCancelAnimation();
          } else if (currentAnimationPage.isConfirmArea()!) {
            startConfirmAnimation();
          }
          break;
        case AnimationType.TYPE_ANIMATION_SLIDE_TURN:
          startFlingAnimation(event.touchDetail);
          break;
        default:
          break;
      }
    }
    currentTouchData = event;
    currentAnimationPage.onTouchEvent(currentTouchData);
  }

  // 设置界面大小
  void setPageSize(Size size) {
    currentAnimationPage.setSize(size);
  }


  //设置绘制
  void onPageDraw(Canvas canvas) {
    currentAnimationPage.onDraw(canvas);
  }

  //获取当前的动画
  int getCurrentAnimation() {
    return currentAnimationType;
  }



  void startConfirmAnimation() {
    Animation<Offset>? animation = currentAnimationPage.getConfirmAnimation(animationController, canvasKey);

    if (animation == null) {
      return;
    }
    setAnimation(animation);

    animationController.forward();
  }

  void startCancelAnimation() {
    Animation<Offset>? animation = currentAnimationPage.getCancelAnimation(animationController, canvasKey);

    if (animation == null) {
      return;
    }

    setAnimation(animation);

    animationController.forward();
  }

  void setAnimation(Animation<Offset> animation) {
    if (!animationController.isCompleted) {
      animation
        ..addListener(() {
          currentState = STATE.STATE_ANIMATING;
          canvasKey.currentContext?.findRenderObject()?.markNeedsPaint();
          // print("addListener:TouchEvent.ACTION_MOVE");
          currentAnimationPage.onTouchEvent(TouchEvent(TouchEvent.ACTION_KEEP, animation.value));
        })
        ..addStatusListener((status) {
          switch (status) {
            case AnimationStatus.dismissed:
              break;
            case AnimationStatus.completed:
              currentState = STATE.STATE_IDE;
              // print("AnimationStatus.completed");
              currentAnimationPage.onTouchEvent(TouchEvent(TouchEvent.ACTION_CANCEL, Offset(0, 0)));
              currentTouchData = TouchEvent(TouchEvent.ACTION_UP, Offset(0, 0));
              animationController.stop();
              break;
            case AnimationStatus.forward:
            case AnimationStatus.reverse:
              currentState = STATE.STATE_ANIMATING;
              break;
          }
        });
    }

    if (animationController.isCompleted) {
      animationController.reset();
    }
  }

  void startFlingAnimation(DragEndDetails details) {
    Simulation? simulation = currentAnimationPage.getFlingAnimationSimulation(animationController, details);

    if (simulation == null) {
      return;
    }

    if (animationController.isCompleted) {
      animationController.reset();
    }

    animationController.animateWith(simulation);
  }

  void interruptCancelAnimation() {
    if (animationController != null && !animationController.isCompleted) {
      animationController.stop();
      currentState = STATE.STATE_IDE;
      // print("interruptCancelAnimation");
      currentAnimationPage.onTouchEvent(TouchEvent(TouchEvent.ACTION_UP, Offset(0, 0)));
      currentTouchData = TouchEvent(TouchEvent.ACTION_UP, Offset(0, 0));
    }
  }

  bool shouldRepaint(CustomPainter oldDelegate, NovelPagePainter currentDelegate) {
    if (STATE.STATE_ANIMATING == currentState) {
      return true;
    }
    if (TouchEvent.ACTION_DOWN == currentTouchData.action) {
      return true;
    }
    NovelPagePainter oldPainter = (oldDelegate as NovelPagePainter);
    return oldPainter.currentTouchData != currentDelegate.currentTouchData;
  }

  void _setAnimationController() {
    animationController.duration = const Duration(milliseconds: 300);

    currentAnimationPage.setAnimationController(animationController);

    if (AnimationType.TYPE_ANIMATION_SLIDE_TURN == currentAnimationType) {
      animationController
        ..addListener(() {
          currentState = STATE.STATE_ANIMATING;
          canvasKey.currentContext?.findRenderObject()?.markNeedsPaint();
          if (!animationController.value.isInfinite &&
              !animationController.value.isNaN) {
            // print("animationController：addListener:TouchEvent.ACTION_MOVE");
            currentAnimationPage.onTouchEvent(TouchEvent(TouchEvent.ACTION_MOVE, Offset(0, animationController.value)));
          }
        })
        ..addStatusListener((status) {
          switch (status) {
            case AnimationStatus.dismissed:
              break;
            case AnimationStatus.completed:
              currentState = STATE.STATE_IDE;
              // print("AnimationStatus.completed111");
              currentAnimationPage.onTouchEvent(TouchEvent(TouchEvent.ACTION_UP, Offset(0, 0)));
              currentTouchData = TouchEvent(TouchEvent.ACTION_UP, Offset(0, 0));
              break;
            case AnimationStatus.forward:
            case AnimationStatus.reverse:
              currentState = STATE.STATE_ANIMATING;
              break;
          }
        });
    }
  }
}

enum STATE { STATE_ANIMATING, STATE_IDE }

